import axios, {AxiosError, AxiosRequestConfig} from "axios";
import {templateReplace} from '@/utils/index'
import { ElMessage } from "element-plus";

declare module 'axios' {
    export interface AxiosRequestConfig {
        templateParam?:Record<string, any>
    }
}

const apiConfig:AxiosRequestConfig = {
    timeout:5000,
    baseURL:"/api"
}

function createAxios(config:AxiosRequestConfig) {
    const axiosInstance = axios.create(config);
    axiosInstance.interceptors.request.use((conf)=>{
        if(conf.templateParam && conf.url){
            conf.url = templateReplace(conf.url,conf.templateParam)
        }
        return conf;
    })
    axiosInstance.interceptors.response.use(res=>res,(err:AxiosError)=>{
        ElMessage.error({type:"error",message:String(err)});
        return err;
    })
    return axiosInstance;
}

export const apiAxios = createAxios(apiConfig)
